import axios, { AxiosRequestConfig } from 'axios'
import { notification } from 'ant-design-vue'
import _ from 'lodash'
import process from 'process'
// import { parseCookies } from 'nookies'
// import { toLogin } from "./auth";

// 日志
const pro: any = process
const logger = pro?.browser ? { log: console.error } : require('../utils/logger').default

const isBrowser = typeof window !== 'undefined'

// 设置全局参数，如响应超时时间，请求前缀等。
const instance = axios.create({
	baseURL: process.env['VUE_APP_API'] || '/',
	timeout: 30000,
	withCredentials: true
})

// Add a request interceptor 请求拦截
instance.interceptors.request.use(
	function (config) {
		// Do something before request is sent
		return config
	},
	function (error) {
		// Do something with request error
		return Promise.reject(error)
	}
)

// Add a response interceptor 响应拦截
instance.interceptors.response.use(
	function (response) {
		// Any status code that lie within the range of 2xx cause this function to trigger
		// Do something with response data
		return response
	},
	function (error) {
		// Any status codes that falls outside the range of 2xx cause this function to trigger
		// Do something with response error
		return Promise.reject(error)
	}
)

// 状态码错误信息
const codeMessage: any = {
	200: '服务器成功返回请求的数据。',
	201: '新建或修改数据成功。',
	202: '一个请求已经进入后台排队（异步任务）。',
	204: '删除数据成功。',
	400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
	401: '用户没有权限（令牌、用户名、密码错误）。',
	403: '用户得到授权，但是访问是被禁止的。',
	404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
	406: '请求的格式不可得。',
	410: '请求的资源被永久删除，且不会再得到的。',
	422: '当创建一个对象时，发生一个验证错误。',
	500: '服务器发生错误，请检查服务器。',
	502: '网关错误。',
	503: '服务不可用，服务器暂时过载或维护。',
	504: '网关超时。'
}

export interface Opt extends AxiosRequestConfig {
	// 是否需要自定义错误提示
	customError: boolean
	// 服务端请求数据时的上下文信息，包含 cookie 信息
	// ctx: any;
	method?: any
}

interface Response<d = any> {
	code: number
	data: d
	message: string
}
//eslint-disable-next-line max-len
function request<d = any>(
	url: string | Partial<Opt>,
	opt: Partial<Opt> = {}
): Promise<Response<d>> {
	let options = opt
	if (_.isPlainObject(url)) {
		options = Object.assign({ method: 'get' }, url, options) as Partial<Opt>
	} else if (_.isString(url)) {
		options = {
			method: 'get',
			url: url as string,
			...options
		}
	} else {
		return Promise.reject({
			code: 406,
			data: null,
			message: '请求参数错误！~'
		})
	}
	let { customError, headers = {}, ...rest } = options
	//ctx,

	// const token = parseCookies(ctx).pandora_tk || ''
	if (['get', 'GET'].includes(options.method)) {
		_.set(rest, 'params', options.data || {})
	} else {
		_.set(rest, 'data', options.data || {})
	}

	// 处理 headers
	_.set(rest, 'headers', {
		// Authorization: `Bearer ${token}`,
		'Content-Type': 'application/json;charset=utf-8',
		...headers
	})

	return new Promise<any>(function (resolve, reject) {
		return instance(rest)
			.then(response => {
				const data = _.get(response, 'data') as {
					code: number
					data: any
					message: string
					msg: string
				}
				const code = _.get(response, 'data.code') as number
				const message = _.get(response, 'data.message') as string
				const msg = _.get(response, 'data.msg') as string
				if (!code || _.toNumber(code) !== 500) {
					//下载模板没有code
					resolve(data)
				}
				// else if (_.toNumber(code) === 200 || _.toNumber(code) === 0) {
				// 	resolve(data)
				// } else if (_.toNumber(code) === 401) {
				// 	// toLogin();
				// 	console.log('此处应该去跳转登录')
				// 	reject(data)
				// }
				else {
					logger.log({
						level: 'error',
						message: message,
						error: { ...response, location: 'request.ts line:142' }
					})
					if (customError && isBrowser) {
						notification.error({
							message: `请求错误 ${code}`,
							description: message || msg
						})
					}
					reject(data)
				}
			})
			.catch(error => {
				if (!error.response) {
					logger.log({
						level: 'error',
						message: error,
						error,
						location: 'request.ts line:159',
						req: rest
					})
					return reject({ code: 500, message: error.message })
				}
				// 响应时状态码处理
				const status = (error.response.data.code || error.response.status) as number
				const errortext = (error.response.error ||
					codeMessage[status] ||
					error.response.statusText) as string
				if (isBrowser) {
					notification.error({
						message: `请求错误 ${status}`,
						description: errortext
					})
					if (_.toNumber(status) === 401) {
						// toLogin();
						console.log('此处应该去跳转登录')
					}
				}
				logger.log({
					level: 'error',
					message: errortext,
					error,
					location: 'request.ts line:182',
					req: rest
				})
				reject({ code: status, message: errortext })
			})
	})
}
export default request
